package de.tum.in.far.threedui.superbrickball.engine;

import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

public class ClockGenerator{
	private long period;
	private long start;
	private Timer timer;
	private TimerTask timerTask;
	private Vector<ClockListener> recievers;
	
	public ClockGenerator(long period)
	{
		this.period = period;
		this.start= -1;
		this.recievers = new Vector<ClockListener>();
		
		this.timer = new Timer();
		this.timerTask = new TimerTask() {
			
			@Override
			public void run() {
				signal();
			}
		};
	}
	
	public void start()
	{
		this.start = System.currentTimeMillis();
		
		this.timer.schedule(this.timerTask, 100, this.period);
	}
	
	public void addClockListener(ClockListener reciever)
	{
		this.recievers.add(reciever);
	}
	
	public void signal()
	{
		long currentVirtualTime = System.currentTimeMillis() - this.start;
		for( ClockListener cr: this.recievers)
		{
			cr.onClockSignal(currentVirtualTime, this.period);
		}
	}

}
